﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace testServer
{
    class Program
    {
        static int conn = 0;
        static void Main(string[] args)
        {
            TcpListener ls = new TcpListener(8888);
            ls.Start(200);
            while (true)
            {
                TcpClient tc = ls.AcceptTcpClient();
                ThreadPool.QueueUserWorkItem(
                    (WaitCallback)delegate(object State)
                {
                    Interlocked.Increment(ref conn);
                    Console.WriteLine(conn + " connected");
                    TcpClient c = (TcpClient)State;
                    try
                    {
                        NetworkStream ns = c.GetStream();
                        byte[] buffer=new byte[1024];
                        IAsyncResult rs = ns.BeginRead(buffer, 0, 1024,
                            (AsyncCallback)delegate(IAsyncResult Ar)
                        {
                            Read(buffer, Ar);
                        }, ns);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        c.Close();
                    }

                },tc
                );
            }
        }

        static void Read(Byte[] buffer, IAsyncResult Ar)
        {
            try
            {
                MemoryStream Ms = new MemoryStream();
                NetworkStream Netstream = (NetworkStream)Ar.AsyncState;
                int ReadCount = Netstream.EndRead(Ar);
                if (ReadCount > 0)
                {
                    Ms.Write(buffer, 0, ReadCount);
                }
                Netstream.BeginWrite(Ms.ToArray(), 0, (int)Ms.Length,
                     (AsyncCallback)delegate(IAsyncResult Arg)
                     {
                         if (Arg.IsCompleted)
                         {
                             ((NetworkStream)Arg.AsyncState).BeginRead(buffer, 0, 1024,
                                 (AsyncCallback)delegate(IAsyncResult Ars)
                             {
                                 Read(buffer, Ars);
                             }, Arg.AsyncState
                                 );
                         }
                     }, Netstream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        
    }
}
